package com.example.demo.controller;

import com.example.demo.enity.User;
import com.example.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@SuppressWarnings({"all"})
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/{id}")
    @ResponseBody
    public User get(@PathVariable("id") Integer id) {
        return userService.getUser(id);
    }

    @RequestMapping("/list1")
    @ResponseBody
    public List<User> list1() {
        List<User> users = userService.findAllUser();
        for (User user : users) {
            System.out.println(user.getUserName());
        }
        return users;
    }

    @RequestMapping("/list2")
    @ResponseBody
    public List<User> list2(@RequestParam(value = "userName", required = false) String userName,
                            @RequestParam(value = "note", required = false) String note) {
        List<User> users = userService.findUsers(userName, note);
        for (User user : users) {
            System.out.println(user.getUserName());
        }
        return users;
    }

    @RequestMapping("/insert")
    @ResponseBody
    public Integer insert(@RequestParam(value = "userName", required = false) String userName,
                          @RequestParam(value = "note", required = false) String note) {
        User user = new User();
        user.setUserName(userName);
        user.setNote(note);
        userService.insertUser(user);
        return user.getId();
    }

    @RequestMapping("/update")
    @ResponseBody
    public Integer update(@RequestParam(value = "id", required = false) Integer id,
                          @RequestParam(value = "userName", required = false) String userName,
                          @RequestParam(value = "note", required = false) String note) {
        User user = userService.getUser(id);
        user.setUserName(userName);
        user.setNote(note);
        userService.updateUser(user);
        return user.getId();
    }

    @RequestMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        return "删除数据[" + userService.deleteUser(id) + "]条";
    }

}
